<?php

declare(strict_types=1);

namespace App\CustHub\Service;

use App\CustHub\Amqp\Producers\SendRecordProducers;
use App\CustHub\Constants\ContactTaskCenterTyperConstants;
use App\CustHub\Constants\MsgTypeConstants;
use App\CustHub\Constants\OpSchemeTypeConstants;
use App\CustHub\Constants\SendConfigConstants;
use App\CustHub\Dto\ContactTcContentDto;
use App\CustHub\Dto\SendRecordProducersDto;
use App\CustHub\Helpers\TagReplacer;
use App\CustHub\Mapper\ChContactMapper;
use App\CustHub\Mapper\ChOpSchemeMapper;
use App\CustHub\Mapper\ChOpSchemeRobotMapper;
use App\CustHub\Model\ChContact;
use App\CustHub\Model\ChCorpTag;
use App\CustHub\Model\ChOpSchemeRobot;
use App\CustHub\Model\ChRobot;
use App\CustHub\Model\ChRoomInviteActiveRoom;
use App\CustHub\Model\ChSendRecord;
use App\CustHub\Model\ChSmartTag;
use App\CustHub\Traits\OpSchemeTrait;
use App\Robot\Dto\CommonJobDto;
use App\Robot\Job\CommonJob;
use App\Robot\Service\SendRobotMessageService;
use Hyperf\Amqp\Producer;
use Hyperf\Collection\Collection;
use Hyperf\Collection\Enumerable;
use Hyperf\Coroutine\Coroutine;
use Hyperf\Di\Annotation\Inject;
use Mine\Abstracts\AbstractService;
use function Hyperf\Collection\collect;
use function Hyperf\Collection\data_get;
use function Hyperf\Coroutine\co;

class ChNewCustomerSchemeService extends AbstractService
{
    use OpSchemeTrait;

    public $mapper;

    protected $type = OpSchemeTypeConstants::NEW_CUSTOMER;

    #[Inject]
    protected ChOpSchemeRobotMapper $schemeRobotMapper;

    #[Inject]
    protected ChContactMapper $contactMapper;

    #[Inject]
    protected ActiveAddFriendService $activeAddFriendService;

    public function __construct(ChOpSchemeMapper $mapper)
    {
        $this->mapper = $mapper;
    }


    public function handlePageItems(array $items,array $params): Enumerable|Collection
    {
        foreach ($items as $k=>$item){
            $cfg = $item['cfg'];

            $cfg['corp_tag_names'] = [];
            if(!empty($cfg['set_corp_tag_ids'])){
                $cfg['corp_tag_names'] = ChCorpTag::query()->whereIn('id',$cfg['set_corp_tag_ids'])->pluck('name')->toArray();
            }

            $cfg['smart_tag_names'] = [];
            if(!empty($cfg['set_smart_tag_ids'])){
                $cfg['smart_tag_names'] = ChSmartTag::query()->whereIn('id',$cfg['set_smart_tag_ids'])->pluck('name')->toArray();
            }
            $items[$k]['cfg'] = $cfg;
        }


        $items = collect($items);

        return $items;
    }

    public function handleSaveData(array $data):array
    {
        if(!empty($data['cfg'])){
            $cfg = json_decode($data['cfg'],true);
        }else{
            $cfg = [
                'trigger_cond' =>[
                    'gender' => [
                        'match_type' => 0,
                        'value' => []
                    ],
                    'corp_tag_ids' => []
                ]
            ];
        }

        $initCfg = [
            'set_corp_tag_ids' => [],
            'set_smart_tag_ids' => [],
            'auto_remark_switch' => 0,
            'auto_remark_content' => "",
            'content' => [
            ]
        ];

        $data['cfg'] = array_merge($initCfg,$cfg);
        return $data;
    }

    public function afterUpdate(mixed $id,array $data)
    {
        if($data['is_default'] == 1){
            //默认方案
            //获取当前方案应用过的机器人
            $robotIds = ChOpSchemeRobot::query()
                ->where('scheme_id',$id)
                ->where('type',$this->type)
                ->pluck('robot_id')
                ->toArray();

            $needDeleteIds = ChOpSchemeRobot::query()
                ->whereIn('robot_id',$robotIds)
                ->where('type',OpSchemeTypeConstants::NEW_CUSTOMER)
                ->where('scheme_id','<>',$id)
                ->whereHas('scheme',function ($query){
                    $query->where('is_default',1);
                })
                ->pluck('id')
                ->toArray();

            if(!empty($needDeleteIds)){
                ChOpSchemeRobot::query()
                    ->whereIn('id',$needDeleteIds)
                    ->delete();
            }
        }
    }

    public function triggerScheme(array $data,ChRobot $robot,$isFriendApply = false): void
    {
        $sender = (string)$data['sender'];
        $key = 'is_trigger_new_customer:'.$robot->id.':'.$sender;
        $redis = redis();
        if($redis->exists($key)){
            return;
        }
        $redis->set($key,1,60);

//        $contact = $this->contactMapper->findByRobotIdAndUserId($robot->id,$sender);
        $contact = ChContact::query()
            ->where('robot_id',$robot->id)
            ->where('user_id',$sender)
            ->first();
        if(empty($contact)){
            return;
        }
        //获取机器人对应的方案
        //获取
        $robotSchemeList = $this->schemeRobotMapper->findRobotScheme($robot['id'],$this->type);
        if(empty($robotSchemeList)){
            return;
        }

        $condSchemeList = $robotSchemeList->filter(function ($item){
            return !empty($item->scheme)  && $item->scheme->is_default == 0;
        });
        $robotScheme = [];
        if($condSchemeList->isNotEmpty()){
            foreach ($condSchemeList as $item){
                $cfg = $item->scheme->cfg;
                $isGenderMatch = true;
                $isAddTypeMatch = true;
                $matchType = data_get($cfg,'gender_match_type',0);
                $addType = data_get($cfg,'add_type',[]);
                if($matchType == 1){
                    $genderArr = data_get($cfg,'gender',[]);
                    $isGenderMatch = !empty($genderArr) && in_array($contact->gender, $genderArr);
                }
                if (!empty($addType)) {
                    $friendAddType = $isFriendApply ? 0 : 1;
                    $isAddTypeMatch = in_array($friendAddType, $addType);
                }
                if($isGenderMatch && $isAddTypeMatch){
                    $robotScheme = $item;
                    break;
                }
            }
        }

        if(empty($robotScheme)){
            $robotScheme = $robotSchemeList->filter(function ($item){
                return !empty($item->scheme) && $item->scheme->is_default == 1;
            })->first();
        }

        if(!empty($robotScheme)){
            $cfg = $robotScheme->scheme->cfg;

            //自动备注
            //主动加好友如果备注了，新客户运营就不用备注了
            $result=$this->activeAddFriendService->autoRemark($contact,true);
            if(!$result){
                $auto_remark_switch = data_get($cfg,'auto_remark_switch',0);
                if($auto_remark_switch == 1){
                    $auto_remark_content = data_get($cfg,'auto_remark_content');
                    if(!empty($auto_remark_content)){
                        $auto_remark_content = TagReplacer::replaceTags($auto_remark_content,[
                            'nickname' => $contact->nickname,
                            'gender' => $contact->gender,
                            'add_time' => datetime($contact->add_customer_time,'Y-m-d')
                        ]);
                        $taskData = new ContactTcContentDto();
                        $taskData->setContactIds([$contact->id]);
                        $taskData->setExtra([
                            'type' => 0,
                            'content' => $auto_remark_content
                        ]);
                        container()->get(ChContactTaskCenterService::class)->addTask($contact->uid,$contact->main_uid,ContactTaskCenterTyperConstants::EDIT_REMARK,$taskData);
                    }
                }
            }

            //企微标签
            $corp_tag_ids = data_get($cfg,'set_corp_tag_ids',[]);
            if(!empty($corp_tag_ids)){
                //企业标签
                $content = new ContactTcContentDto();
                $content->setContactIds([$contact->id]);
                $content->setTagIds(array_unique($corp_tag_ids));

                $contact->corpTags()->sync($corp_tag_ids);
                container()->get(ChContactTaskCenterService::class)->addTask($contact->uid,$contact->main_uid,ContactTaskCenterTyperConstants::PUT_ON_CORP_TAG,$content);
            }

            //智能标签
            $smart_tag_ids = data_get($cfg,'set_smart_tag_ids',[]);
            if(!empty($smart_tag_ids)){
                //智能标签
                $content = new ContactTcContentDto();
                $content->setContactIds([$contact->id]);
                $content->setTagIds(array_unique($smart_tag_ids));
                container()->get(ChContactTaskCenterService::class)->addTask($contact->uid,$contact->main_uid,ContactTaskCenterTyperConstants::PUT_ON_SMART_TAG,$content);
            }

            $sendContent = data_get($cfg,'content');
            //发送消息
            if(!empty($sendContent)){
                foreach ($sendContent as $k=>$content){
                    if($content['msg_type'] == MsgTypeConstants::TEXT){
                        $sendContent[$k]['content'] = TagReplacer::replaceTags($content['content'],[
                            'call_name_nickname' => !empty($contact->call_name) ? $contact->call_name : $contact->nickname,
                            'gender' => $contact->gender,
                            'add_time' => datetime($contact->add_customer_time,'Y-m-d')
                        ]);
                    }
                }
                co(function () use ($contact,$sendContent,$robot){
                    $msgLimit = 0;
                    foreach ($sendContent as $content){
                        $extra = data_get($content,'extra.limit',[]);
                        //单位  1秒 2分钟
                        $unit = data_get($extra,'unit',1);
                        $limit = data_get($extra,'value',0);
                        if($unit == 2){
                            $limit = $limit * 60;
                        }elseif ($unit == 3){
                            $limit = $limit * 60 * 60;
                        }
                        $msgLimit = $msgLimit + $limit;

                        if ($msgLimit > 0) {
                            Coroutine::sleep($msgLimit);
                        }
                        stdout_log()->info("新客户运营发送消息时间间隔-".$msgLimit.'-'.json_encode($content['content']));

                        if($content['msg_type'] !== MsgTypeConstants::CROWD){
                            $messageData = [
                                'robot_id' => $robot->id,
                                'to_id' => $contact->user_id,
                                'msg_type' => $content['msg_type'],
                                'content' => $content['content']
                            ];
                            container()->get(SendRobotMessageService::class)->handle($messageData);
                        }else{
                            $messageData = [
                                'robot_id' => $robot->id,
                                'scheme_id' => $content['content'],
                                'user_id' => $contact->user_id,
                                'gender' => $contact->gender
                            ];
                            container()->get(ChRoomInviteSchemeService::class)->handle($messageData);
                        }
                    }
                });
            }
        }

    }
}